package leetcode.code0885;

public class Solution {
	int[] x = new int[] { 0, 1, 0, -1 };
	int[] y = new int[] { 1, 0, -1, 0 };

	public int[][] spiralMatrixIII(int rows, int cols, int r, int c) {
		int rc = rows * cols;
		int[][] ans = new int[rc][2];
		int cnt = 0, d = 0, p = 0, move = 1;
		while (cnt < rc) {
			for (int i = 0; i < move; i++) {
				if (r < rows && c < cols && r > -1 && c > -1) {
					cnt += 1;
					ans[p][0] = r;
					ans[p][1] = c;
					p++;
				}
				r += x[d];
				c += y[d];
			}
			d++;
			d %= 4;
			if (d == 2 || d == 0) {
				move++;
			}
		}
		return ans;
	}
}
